package com.xin.springbootjurisdiction.service.impl;

import com.xin.springbootjurisdiction.dataobject.AdminRole;
import com.xin.springbootjurisdiction.repository.AdminRoleRepository;
import com.xin.springbootjurisdiction.service.AdminRoleService;
import com.xin.springbootjurisdiction.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.xml.crypto.dsig.keyinfo.KeyName;

@Service
@Slf4j
public class AdminRoleSerivceImpl implements AdminRoleService {
    @Autowired
    private AdminRoleRepository adminRoleRepository;

    /**
     * 创建关联
     *
     * @param adminRole
     * @return
     */
    @Override
    @Transactional
    public AdminRole create(AdminRole adminRole) {
        if (ObjectUtils.isEmpty(adminRole)) {
            return null;
        }
        if (StringUtils.isEmpty(adminRole.getAdminId()) || StringUtils.isEmpty(adminRole.getRoleId())) {
            return null;
        }
        AdminRole one = findOne(adminRole);
        if (!ObjectUtils.isEmpty(one)){
             return null;
        }
        adminRole.setId(KeyUtil.genUniqueKey());
        AdminRole save = adminRoleRepository.save(adminRole);
        if (!ObjectUtils.isEmpty(save)){
             return save;
        }
        return null;
    }

    /**
     * 删除关联
     * @param adminRole
     * @return
     */
    @Override
    @Transactional
    public boolean delete(AdminRole adminRole) {
        if (ObjectUtils.isEmpty(adminRole)) {
            return false;
        }
        if (StringUtils.isEmpty(adminRole.getAdminId()) || StringUtils.isEmpty(adminRole.getRoleId())) {
            return false;
        }
        AdminRole role = findOne(adminRole);
        if (ObjectUtils.isEmpty(role)){
             return false;
        }
        adminRoleRepository.delete(role);
        return true;
    }

    /**
     * 查找
     * @param adminRole
     * @return
     */
    @Override
    public AdminRole findOne(AdminRole adminRole) {
        if (ObjectUtils.isEmpty(adminRole)) {
            return null;
        }
        if (StringUtils.isEmpty(adminRole.getAdminId()) || StringUtils.isEmpty(adminRole.getRoleId())) {
            return null;
        }
        AdminRole role = adminRoleRepository.findByAdminIdAndRoleId(adminRole.getAdminId(), adminRole.getRoleId());

        return role;
    }
}
